import React from 'react';
import * as Icons from '@ant-design/icons';
import menuArr from '../../config/index'
import { Layout, Menu } from 'antd';
import { useSelector } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom'
const { Sider } = Layout;

// 处理菜单数据
const getItems = (menuArr) => {
  const items = menuArr.map((menu) => {
    const item = {
      key: menu.name,
      icon: getIcon(menu.icon),
      label: menu.label,
    }
    if (menu.children && menu.children.length > 0) {
      item.children = getItems(menu.children)
    }
    return item
  })

  return items
}

// 生成图标元素
const getIcon = (index) => {
  return React.createElement(Icons[index])
}

// 获取路由
const findFullPath = (key, menuArr, parentPath = '') => {
  for (let menu of menuArr) {
    let fullPath = parentPath ? `${parentPath}/${menu.path}` : menu.path;
    if (menu.name === key) return fullPath;
    if (menu.children) {
      let childPath = findFullPath(key, menu.children, fullPath);
      if (childPath) return childPath;
    }
  }
  return key;
};

export default function CommonMenu() {
  const navigate = useNavigate()
  const location = useLocation();  // 获取当前路径
  const collapsed = useSelector(s => s.collapsed)
  const items = getItems(menuArr)

  // 通过当前路径查找对应的菜单项 key
  const getSelectedKey = () => {
    const path = location.pathname;
    for (let menu of menuArr) {
      // 通过菜单项路径匹配当前路径
      const fullPath = findFullPath(menu.name, menuArr);
      if (fullPath && path.includes(fullPath)) {
        return menu.name;
      }
      if (menu.children) {
        for (let child of menu.children) {
          const childFullPath = findFullPath(child.name, menuArr, 'other');
          if (path.includes(childFullPath)) {
            return child.name;
          }
        }
      }
    }
    return ''; // 默认返回空，表示没有匹配的项
  }

  const handleClick = (e) => {
    const fullPath = findFullPath(e.key, menuArr);
    console.log(fullPath)
    navigate(`/${fullPath}`);
  }

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <h3 style={{ color: '#fff', margin: '20px 10px' }}>{!collapsed ? "通用后台管理系统" : "后台"}</h3>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={[getSelectedKey()]}  // 设置当前选中的菜单项
        items={items}
        onClick={handleClick}
      />
    </Sider>
  )
}
